/*
 * Copyright (c) 2007 jNetX.
 * http://www.jnetx.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * jNetX. You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license
 * agreement you entered into with jNetX.
 *
 * $Id$
 */
package com.jnetx.javax.sip.header;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.ParseException;

import com.jnetx.javax.sip.util.ByteArrayUtil;
import com.jnetx.javax.sip.address.AddressFactoryImpl;

/**
 * @author <a href="mailto:dparhonin@jnetx.ru">Dmitry Parhonin</a>
 * @version $Revision$
 */
public class ToHeaderParser extends ParametrizedHeaderParserBase<ToHeaderImpl> {
    private final static Log logger = LogFactory.getLog(ToHeaderParser.class);

    protected Log getLogger() {
        return logger;
    }

    public ToHeaderImpl createLazily(byte[] data, int start, int end) {
        return new ToHeaderImpl(data, start, end);
    }

    public ToHeaderImpl[] parse(ToHeaderImpl header, byte[] data, int start, int end) throws ParseException {
        if (header == null) header = new ToHeaderImpl();
        int startOfData = ByteArrayUtil.firstMissing(data, ' ', start, end);
        if (startOfData == -1)
            fail("Cannot parse the header!", start);
        int endOfPart = ByteArrayUtil.lastMissing(data, ' ', startOfData, end);
        if (endOfPart == -1)
            endOfPart = start;
        else
            endOfPart++;
        final int leftQuote = ByteArrayUtil.firstOccurence(data, '<', startOfData, endOfPart);
        final int startOfParameter;
        if (leftQuote != -1) {
            final int rightQuote = ByteArrayUtil.lastOccurence(data, '>', leftQuote, endOfPart);
            startOfParameter = ByteArrayUtil.firstOccurence(data, ';', rightQuote + 1, endOfPart);
        } else {
            startOfParameter = ByteArrayUtil.firstOccurence(data, ';', startOfData, endOfPart);
        }
        final int endOfData = startOfParameter == -1 ? endOfPart : startOfParameter;
        header.setAddress(AddressFactoryImpl.createAddressLazily(data, startOfData, endOfData));
        if (startOfParameter != -1)
            parseParameters(header, data, startOfParameter, endOfPart);
        return new ToHeaderImpl[]{header};
    }
}
/*
 * $Log$
 */